<?php
namespace app\mobile\controller;

use dc\controller\HomeBaseController;
use dragon\Support\Wechat;
use dragon\User\ThirdPartyUser;
use dragon\User\WechatUser;
use think\Db;
use think\Request;
use think\Session;

class BaseController extends HomeBaseController
{
    protected $user, $token;
    protected $logId;
    protected $perpage;

    /**
     * 构造函数
     * @param Request $request Request对象
     * @access public
     */
    public function __construct(Request $request = null)
    {
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Headers: Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With');

        if($request->method() == 'OPTIONS') {
            exit(json_encode_cn($this->success('success')));
        }
        if (is_null($request)) {
            $request = Request::instance();
        }

        $this->token = $request->param('token', date('YmdHis').mt_rand(100000, 999999), 'trim');
        // 测试
//        $this->token = '15299694381580.006983';

        $this->request = $request;
        $this->perpage = $this->request->param('per_page', 10, 'intval');


        // 前置操作方法
        if ($this->beforeActionList) {
            foreach ($this->beforeActionList as $method => $options) {
                is_numeric($method) ?
                    $this->beforeAction($options) :
                    $this->beforeAction($method, $options);
            }
        }
        parent::__construct($request);

        $this->logId = Db::name('api_log')->insertGetId([
            'request_uri'   => $_SERVER['REQUEST_URI'],
            'file_string'   => json_encode_cn($_FILES),
            'input'         => file_get_contents('php://input'),
            'post_string'   => json_encode_cn($_POST),
            'send_content'  => json_encode_cn($this->sendContent),
            'update_time'   => date('Y-m-d H:i:s'),
            'create_time'   => date('Y-m-d H:i:s'),
        ]);

        $this->checkUserLogin();

        if($this->user['user_status'] == 0) {
            exit(json_encode_cn($this->error('您的账户已停用，如有疑问请联系客服人员')));
        }
    }

    /**
     * 错误返回
     * @param string $errorMessage
     * @param null $errorCode
     * @param string $data
     * @param int $wait
     * @param array $header
     * @return array
     */
    protected function error($errorMessage = '', $errorCode = null, $data = '', $wait = 3, array $header = [])
    {
        $result = [
            'status'    => 0,
            'err_code'  => $errorCode,
            'err_msg'   => $errorMessage,
            'token'     => $this->token,
        ];

        if($this->logId) {
            Db::name('api_log')->where('id', $this->logId)->update([
                'response' => json_encode_cn($result),
                'update_time'   => date('Y-m-d H:i:s'),
            ]);
        }
        return $result;
    }

    /**
     * 正确返回
     * @param string $response
     * @param null $url
     * @param string $data
     * @param int $wait
     * @param array $header
     * @return array
     */
    protected function success($response = '', $url = null, $data = '', $wait = 3, array $header = [])
    {
        $result = [
            'status'    => 1,
            'result'  => $response,
            'token'     => $this->token,
        ];
        Db::name('api_log')->where('id', $this->logId)->update([
            'response' => json_encode_cn($result),
            'update_time'   => date('Y-m-d H:i:s'),
        ]);
        return $result;
    }

    public function redirect($url, $params = [], $code = 302, $with = [])
    {
        $result = [
            'status'    => $code,
            'url'       => $url,
            'result'    => $params,
            'token'     => $this->token,
        ];
        Db::name('api_log')->where('id', $this->logId)->update([
            'response' => json_encode_cn($result),
            'update_time'   => date('Y-m-d H:i:s'),
        ]);
        exit(json_encode_cn($result));
    }


    // 登录判断
    public function checkUserLogin()
    {
        // 测试数据
        $wechatUser = ThirdPartyUser::get(['token' => $this->token]);

        $wechat = Wechat::sdk();

        $oauthAccessToken = [];
        if (!$wechatUser) {
            //尝试获取token。若获取失败，则表示用户通过的是非Oauth 2.0入口进入应用
            if (!$oauthAccessToken = $wechat->getOauthAccessToken()) {
                return $this->redirect($wechat->getOauthRedirect($this->weChatHomeUrl(), '1', 'snsapi_userinfo'));
            }
        } else {
            // 存在 则验证是否过期
            $isexpires = $wechat->getOauthAuth($wechatUser['access_token'], $wechatUser['openid']);            //验证access_token是否过期

            // 过期则刷新
            if (!$isexpires && !$this->local()) {
                $oauthAccessToken = $wechat->getOauthRefreshToken($wechatUser['refresh_token']);

                // 更新
                $oauthAccessToken['token'] = $this->token;
                $wechatUser->save($oauthAccessToken);
            }
        }

        $this->wechatUserInit($wechat, $wechatUser, $oauthAccessToken);
    }

    // 信息初始化

    /**
     * @param $wechat
     */
    private function wechatUserInit($wechat, $weUser, $oauthAccessToken)
    {
        // 获取用户信息
        $weUser or $weUser = WechatUser::getByOpenid($oauthAccessToken['openid']);

        // 不存在，则注册
        if (!$weUser) {
            // 不存在就重新注册
            $weInfo = $wechat->getUserInfo($oauthAccessToken['openid']);
//            $weInfo = array ( 'subscribe' => 1, 'openid' => 'oQHZq0mp9edmIYFQs7bx636q5OAM', 'nickname' => 'Dr. Dragon O_o 🙏', 'sex' => 1, 'language' => 'zh_CN', 'city' => '青岛', 'province' => '山东', 'country' => '中国', 'headimgurl' => 'http://thirdwx.qlogo.cn/mmopen/DAMlJ2KrwtLcZuLnjxpFPhFPG8FpHhJwCgzOotMa6LGnoyYdibgpWDq4rfmDIlxicGgAXGYVibe4PLCaSjQzIzgrUk2vnW9Mb5q/132', 'subscribe_time' => 1503618767, 'remark' => '', 'groupid' => 0, 'tagid_list' => array ( ), 'subscribe_scene' => 'ADD_SCENE_QR_CODE', 'qr_scene' => 0, 'qr_scene_str' => '', );
            $weInfo['token'] = $this->request->param('token');

            $weUser = WechatUser::registerThirdPartyUser($weInfo);
        } elseif ($weUser['token'] != $this->token) {
            $weUser->save(['token' => $this->token]);
        }

        $this->setUser($weUser->user);
    }

    protected function setUser($user) {
        $this->user = $user;
        config('user_info', $user);
        $this->assign("user_info", $user);
    }

    /**
     * 获取当前页面完整URL地址
     */
    private function weChatHomeUrl()
    {
        $url = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        return $url . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . '/wap/pages/home/index.html';
    }

    // 是否为本地测试
    function local()
    {
        return DIRECTORY_SEPARATOR == '\\';
    }

}
